package com.econ.powercloud.ems.timing.report.prometheus.callback;

import com.econ.powercloud.console.facade.utils.CacheKeyUtils;
import com.econ.powercloud.ems.common.util.JacksonExtUtil;
import com.econ.powercloud.ems.util.AsyncHttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 多个data
 */
@Component
public class PrometheusNodeHealthyCallback implements AsyncHttpClientUtil.StringFutureCallback {

    final private String category = "computer";

    final private String item = "nodeHealthy";

    final private Integer MAX_INSTANCE_COUNT = 10;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void success(String content) {
        Map<String, String> prometheusResult = JacksonExtUtil.flatJsonToMap(content);
        String instanceKeyTemplate = "data.result[%s].metric.instance";
        String valueKeyTemplate = "data.result[%s].value[1]";
        for(int i = 0; i < MAX_INSTANCE_COUNT ; i++){
            String instanceKey = String.format(instanceKeyTemplate, i);
            if(!prometheusResult.containsKey(instanceKey)){
                break;
            }
            String instance = (String)prometheusResult.get(instanceKey).replaceAll(":", "-");
            String value = prometheusResult.get(String.format(valueKeyTemplate, i));
            String redisKey = CacheKeyUtils.getMonitorDataKey(instance, category);
            HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
            hashOperations.put(redisKey, item, value);
        }


    }
}
